//有三个线程，分别只能打印A，B和C
//要求按顺序打印ABC，打印10次
//输出示例：
//ABC
//ABC
//ABC
//ABC
//ABC
//ABC
//ABC
//ABC
//ABC
//ABC
public class Homework {
    public static int flag = 0;//0-A 1-B 2-C   %3
    public static Object locker = new Object();
    public static void main(String[] args) {
        //没有到自己线程的回合,就wait,所以每个线程都有一个notifyAll
        Thread a = new Thread(()->{
           //输出A
            for (int i = 0; i < 10; ) {
                synchronized (locker){
                    if (flag%3==0){
                        flag++;
                        System.out.print("A");
                        i++;
                        locker.notifyAll();
                    }else {
                        //不是自己的回合
                        try {
                            locker.wait();//进入等待
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        Thread b = new Thread(()->{
           //输出B
            for (int i = 0; i < 10; ) {
                synchronized (locker){
                    if (flag%3==1){
                        flag++;
                        System.out.print("B");
                        i++;
                        locker.notifyAll();
                    }else{
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        Thread c = new Thread(()->{
           //输出C
            for (int i = 0; i < 10; ) {
                synchronized (locker){
                    if (flag%3==2){
                        flag++;
                        System.out.println("C");
                        i++;
                        locker.notifyAll();
                    }else{
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        a.start();
        b.start();
        c.start();
    }
}
